//导入配置文件, 封装请求oss文件
const env = require('config.js');
const base64 = require('base64.js');
require('hmac.js');
require('sha1.js');
const Crypto = require('crypto.js');

const uploadFile = function(filePath, path,successc,failc) {
  if (!filePath || filePath.length < 3) {
    wx.showModal({
      title: '图片错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
  console.log('正在上传图片.........');
  //存放图片命名格式：时间戳 + 和后缀为.png格式的图片文件；
  // const aliyunFileKey = path + new Date().getTime() + '.png';
  const aliyunFileKey = path + Date.parse(new Date());
  //OSS地址，https
  const aliyunServerURL = env.uploadImageUrl;
  const accessid = env.OSSAccessKeyId;
  //图片转码算法 
  const policyBase64 = getPolicyBase64();
  const signature = getSignature(policyBase64);
  //图片返回的地址url
  // const imgUrl = aliyunServerURL + aliyunFileKey
  // //转化为字符串地址
  // const newImgUrl = JSON.stringify(imgUrl)

  wx.uploadFile({
    url: aliyunServerURL, //开发者服务器 url
    filePath: filePath, //要上传文件资源的路径
    name: 'file', //file
     formData: {
       'key': aliyunFileKey,
       'policy': policyBase64,
       'OSSAccessKeyId': accessid,
       'signature': signature,
       'success_action_status': '200',
     },
      header: {  
       "Content-Type": "multipart/form-data"  
     },  
    //  success: (res) => {
    //   if (res.statusCode === 200) {
  
    //     console.log('上传成功，图片地址为:' + newImgUrl)
    //   }
    // },
    // fail: err => {
    //   console.log(err);
    // }
    success: function (res) {
      if (res.statusCode != 200) {
         failc(new Error('上传错误:' + JSON.stringify(res)))
         return;
      }
      successc(aliyunServerURL + aliyunFileKey);
   },
   fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      failc(err);
   },
  })
}

const getPolicyBase64 = function() {
  let date = new Date();
  date.setHours(date.getHours() + env.timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，无法通过此policy上传文件
    "conditions": [
      ["content-length-range", 0, 10 * 1024 * 1024] // 设置上传文件的大小限制为10MB
    ]
  };

  const policyBase64 = base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function(policyBase64) {
  const accesskey = env.AccessKeySecret;
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
}

module.exports = uploadFile;